#include <SPI.h>
#include <LoRa.h>
#include <Console.h>
#define Button1 2
#define Button2 4

unsigned int ButtonState1;
unsigned int ButtonState2;
int start_flag;
int num;
int num_flag1,num_flag2;
int sf;
void keyscan();
void setup() {
  Bridge.begin(115200);
  Console.begin();
  start_flag=0;
  
  sf=7;
  pinMode(Button1,INPUT);
  pinMode(Button2,INPUT);
  
  //Serial.begin(9600);
 // while (!Serial);
  num=0;
  Console.println("LoRa Receiver");
  

  if (!LoRa.begin(433E6)) {
    Console.println("Starting LoRa failed!");
    while (1);
  }
  LoRa.setSpreadingFactor(12);
  LoRa.setSignalBandwidth(125E3);
  LoRa.setCodingRate4(5);
  LoRa.setTxPower(20);
  LoRa.setSyncWord(0x34); 
  
  LoRa.disableCrc();
  /*while(!start_flag)
  {
    Serial.print("sf: ");
    Serial.println(sf);
    
    keyscan();
    delay(500);
    }*/
}

void loop() {
  // try to parse packet
  String All_Paket;
  String Paket_num_char;
  char Paket;
  int Paket_num=0;
  int packetSize = LoRa.parsePacket();
  if (packetSize) {
    // received a packet
  //  Serial.print("Received packet '");
      num_flag1=0;
      num_flag2=0;
    // read packet
    while (LoRa.available()) {
      Paket=(LoRa.read());
      if(Paket=='|')
      {
        num_flag1=1;
      }
      
      if(!num_flag1)
      All_Paket=All_Paket+Paket;  
           
      if(num_flag2)
      {
        Paket_num_char=Paket_num_char+Paket;
        Paket_num++;
        }
        if(Paket=='|')
      {
        num_flag2=1;
      }
      
    }
    if(All_Paket.length()<=(Paket_num_char.toInt()+1))
    {
      //Serial.print(All_Paket);
         for(int j=0; All_Paket[j]; j++){
         outc(All_Paket[j]);
     }
    
    //Serial.print(All_Paket.length());
    //Serial.print(Paket_num_char.toInt());
    num++;
    Console.print("'the lose number is ");
    Console.print(Paket_num_char.toInt()-num);
    Console.print("'the receive number is ");
    Console.print(num);
    Console.print("'the send number is ");
    Console.print(Paket_num_char.toInt());
    // print RSSI of packet
    Console.print("' with RSSI ");
    Console.print(LoRa.packetRssi());
    Console.print("' with SNR ");
    Console.println(LoRa.packetSnr());
    }
  }
}

void outc(char c)
{
  unsigned char k = 0x80;
  for (int i=0; i<8; i++, k >>= 1){
    if (c & k){
      Console.print("1");
        }else{
      Console.print("0");
        }
  }

}
void keyscan()
{
  
  if(digitalRead(Button1)==HIGH)
  {
      
          sf++;
          if(sf>12)
          sf=1;
          while(digitalRead(Button1));
        
    }
    if(digitalRead(Button2)==HIGH)
  {
      
          start_flag=1;
          while(digitalRead(Button2));
        
    }
    //Serial.println(ButtonState2);
  }
